﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using StockModel;
using Utils;

namespace StockAnalyst2.Chart
{
	internal class QuotationSourceFinder
	{
		#region Attributes

		private readonly RawStockDataSource _rawStockDataSource;
		private readonly QuotationDataSource _quotationDataSource;
		private readonly ObservableCollection2<StockGroup> _realTimeGroups;

		#endregion

		#region Public Methods

		public QuotationSourceFinder(RawStockDataSource rawStockDataSource, ObservableCollection2<StockGroup> realTimeGroups, QuotationDataSource quotationDataSource)
		{
			_rawStockDataSource = rawStockDataSource;
			_realTimeGroups = realTimeGroups;
			_quotationDataSource = quotationDataSource;
		}

		public ReadWriteLockedObservableCollection<Quotation> Find(string stockName)
		{
			StockGroupItem result = null;

			int index = 0;
			while (result == null && index < _realTimeGroups.Count)
			{
				ObservableCollection2<StockGroupItem> stocks = _realTimeGroups[index].Items.GetReadLock();
				try
				{
					result = stocks.FirstOrDefault(stock => stock.Item.Id.Name == stockName);
				}
				finally
				{
					_realTimeGroups[index].Items.FreeReadLock();
				}
				
				index++;
			}

			if (result == null)
			{
				throw new InvalidDataException(string.Format("There is no stock with name {0} in the collection of realtime stocks", stockName));
			}

			return result.Item.QuotationCalendar.GetLatestAvailableDay().Quotations;
		}

		public ReadWriteLockedObservableCollection<Quotation> Find(string stockName, DateTime day)
		{
			ReadWriteLockedObservableCollection<Quotation> result = null;

			IEnumerable<Stock> stocks = _rawStockDataSource.GetStocks(stockName);
			foreach (Stock stock in stocks)
			{
				if (_quotationDataSource.ExistDay(stock, day))
				{
					ExchangeMarket market = _rawStockDataSource.GetMarket(stock, day);
					result = new ReadWriteLockedObservableCollection<Quotation>(Properties.Settings.Default.MaxWaitWriteLockSeries);
					ObservableCollection2<Quotation> quotations = result.GetWriteLock();
					try
					{
						quotations.AddRange(_quotationDataSource.GetQuotations(stock, day, market));
					}
					finally 
					{
						result.FreeWriteLock();
					}
				}
			}

			if (result == null)
			{
				throw new InvalidDataException(string.Format("There is no stock with name {0} with data for the day {1}", stockName, day));
			}

			return result;
		}


		#endregion
	}
}
